/**
 * 二次封装axios
 */
import axios from 'axios'
import {
    commonDefinition
} from '../store'

// 实现多环境配置
export const baseURL =
    import.meta.env.MODE === "development" ? '/wanxiang' : 'http://www.shuiyue.info:15666'

const Axios = axios.create({
    baseURL,
    timeout: 5000
})

let noInterceptorUrls = [
    '/get/code',
    '/login/byphone'
]
Axios.interceptors.request.use(function (config) {
    // debugger
    if (noInterceptorUrls.includes(config.url)) {
        return config
    }
    // 从仓库中获取token
    let token = commonDefinition().getToken
    if (!!token) {
        config.headers.token = token
        return config
    }

    return Promise.reject({
        code: 1,
        message: '用户的token丢失'
    })
})

export default function Ajax(req) {
    if (!req || !req.url) throw new TypeError('请求对象没有传递或url地址参数没有传递')
    return new Promise(resolve => {
        Axios.request({
            url: req.url,
            method: req.method || 'POST',
            data: req.data || {},
            params: req.params || {}
        }).then(({
            data
        }) => {
            resolve(data)
        }).catch(e => {
            resolve(e)
        })
    })
}